package com.lktx.sso.admin.service;

import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lktx.sso.admin.entity.*;
import com.lktx.sso.admin.mapper.SsoAppAccessPolicyMapper;
import com.lktx.sso.admin.mapper.SsoAppMapper;
import com.lktx.sso.admin.mapper.SsoOrganizationMapper;
import com.lktx.sso.admin.mapper.SsoUserGroupMappingMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * app分组 服务类
 *
 */
@Slf4j
@Bean
public class SsoAppService {

    @Autowired
    private SsoAppMapper mapper;

    @Autowired
    private SsoUserGroupMappingMapper ssoUserGroupMappingMapper;

    @Autowired
    private SsoAppAccessPolicyMapper ssoAppAccessPolicyMapper;

    @Autowired
    private SsoOrganizationMapper ssoOrganizationMapper;

    /**
     * 分页查询列表
     *
     * @param page   分页对象
     * @param entity 查询实体
     * @return 所有数据
     */
    public Page<SsoApp> page(Page<SsoApp> page, SsoApp entity) {
        return mapper.paginateWithRelations(page,new QueryWrapper()
                    .like(SsoApp::getAppName, entity.getAppName(), StrUtil.isNotEmpty(entity.getAppName()))
                    .like(SsoApp::getAppIcon, entity.getAppIcon(), StrUtil.isNotEmpty(entity.getAppIcon()))
                    .like(SsoApp::getClientId, entity.getClientId(), StrUtil.isNotEmpty(entity.getClientId()))
                    .like(SsoApp::getClientSecret, entity.getClientSecret(), StrUtil.isNotEmpty(entity.getClientSecret()))
                    .like(SsoApp::getRemark, entity.getRemark(), StrUtil.isNotEmpty(entity.getRemark()))
                    .like(SsoApp::getAppType, entity.getAppType(), StrUtil.isNotEmpty(entity.getAppType()))
                .orderBy(SsoApp::getSsoAppId,false)
        );
    }

    /**
     * 不分页查询列表
     *
     * @param entity 实体对象
     * @return 查询结果
     */
    public List<SsoApp> list(SsoApp entity) {
        return mapper.selectListWithRelationsByQuery(new QueryWrapper()
                    .like(SsoApp::getAppName, entity.getAppName(), StrUtil.isNotEmpty(entity.getAppName()))
                    .like(SsoApp::getAppIcon, entity.getAppIcon(), StrUtil.isNotEmpty(entity.getAppIcon()))
                    .like(SsoApp::getClientId, entity.getClientId(), StrUtil.isNotEmpty(entity.getClientId()))
                    .like(SsoApp::getClientSecret, entity.getClientSecret(), StrUtil.isNotEmpty(entity.getClientSecret()))
                    .like(SsoApp::getRemark, entity.getRemark(), StrUtil.isNotEmpty(entity.getRemark()))
                    .like(SsoApp::getAppType, entity.getAppType(), StrUtil.isNotEmpty(entity.getAppType()))
                .orderBy(SsoApp::getSsoAppId,false)
        );
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    public SsoApp getById(Integer id) {
        return mapper.selectOneById(id);
    }
    public SsoApp getByClientId(String clientId) {
        return mapper.selectOneByQuery(QueryWrapper.create().eq(SsoApp::getClientId, clientId));
    }


    /**
     * 新增单条数据
     *
     * @param entity 实体对象
     */
    public void save(SsoApp entity) {
        entity.setClientId(IdUtil.fastSimpleUUID());
        entity.setClientSecret(IdUtil.fastSimpleUUID());
        entity.setStatus(0);
        mapper.insert(entity);
    }

    /**
     * 修改单条数据
     *
     * @param entity 实体对象
     */
    public void update(SsoApp entity) {
        mapper.update(entity);
    }

    /**
     * 批量删除数据
     *
     * @param ids 主键集合
     */
    public void deleteByIds(List<Integer> ids) {
        mapper.deleteBatchByIds(ids);
    }



    public List<SsoApp> getAppByUser(SsoUser ssoUser){
        //获取用户组
        Set<Integer> groupIds = ssoUserGroupMappingMapper.selectListByQuery(QueryWrapper.create().eq(SsoUserGroupMapping::getSsoUserId, ssoUser.getSsoUserId())).stream().map(SsoUserGroupMapping::getSsoUserGroupId).collect(Collectors.toSet());
        //查询用户的组织id和父级ID
        Set<Integer> organizationIds = ssoOrganizationMapper.getParentOrganizationIds(ssoUser.getSsoOrganizationId());

        List<SsoAppAccessPolicy> ssoAppAccessPolicies = ssoAppAccessPolicyMapper.selectListByQuery(
                QueryWrapper.create().or(r -> {
                    r.and(k -> {
                        k.eq(SsoAppAccessPolicy::getSubjectType, SsoAppAccessPolicy.SubjectType.USER_GROUP);
                        k.in(SsoAppAccessPolicy::getSubjectId, groupIds);
                        k.eq(SsoAppAccessPolicy::getEnabled, true);
                    });
                },!groupIds.isEmpty()).or(r -> {
                    r.and(k -> {
                        k.eq(SsoAppAccessPolicy::getSubjectType, SsoAppAccessPolicy.SubjectType.USER);
                        k.eq(SsoAppAccessPolicy::getSubjectId, ssoUser.getSsoUserId());
                        k.eq(SsoAppAccessPolicy::getEnabled, true);
                    });
                }).or(r -> {
                    r.and(k -> {
                        k.eq(SsoAppAccessPolicy::getSubjectType, SsoAppAccessPolicy.SubjectType.ORGANIZATION);
                        k.in(SsoAppAccessPolicy::getSubjectId, organizationIds);
                        k.eq(SsoAppAccessPolicy::getEnabled, true);
                    });
                },!organizationIds.isEmpty())
        );
        if (ssoAppAccessPolicies.isEmpty()){
            return null;
        }
        Set<Integer> collect = ssoAppAccessPolicies.stream().map(SsoAppAccessPolicy::getSsoAppId).collect(Collectors.toSet());
        return mapper.selectListWithRelationsByQuery(QueryWrapper.create().in(SsoApp::getSsoAppId,collect ));
    }


}